package cn.winwintech.screenlocker

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.admin.DevicePolicyManager
import android.content.ComponentName
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.lifecycle.lifecycleScope
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import cn.winwintech.screenlocker.databinding.ActivityMainBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private var devicePolicyManager: DevicePolicyManager? = null
    private var componentName: ComponentName? = null

    private lateinit var enableAdminLauncher: ActivityResultLauncher<Intent>
    private var mAlertDialog: AlertDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val prefs = getSharedPreferences("privacy", MODE_PRIVATE)
        val agreed = prefs.getBoolean("agreed", false)
        if (!agreed) {
            // 已同意，直接跳转到主界面
            val intent = Intent(this, PrivacyActivity::class.java)
            startActivity(intent)
            finish()
            return
        }

        devicePolicyManager = getSystemService(DEVICE_POLICY_SERVICE) as DevicePolicyManager?
        binding = ActivityMainBinding.inflate(layoutInflater)

        setContentView(binding.root)
        componentName = ComponentName(this, AdminReceiver::class.java)

        enableAdminLauncher = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            if (result.resultCode != RESULT_OK) {
                Toast.makeText(this, "设备管理权限未授予，无法使用锁屏功能", Toast.LENGTH_SHORT)
                    .show()
            }
        }

        val listener: (v: View) -> Unit = { view ->

            var minutes = 0L
            when (view.id) {
                R.id.lock_10 -> {
                    minutes = 10
                }

                R.id.lock_20 -> {
                    minutes = 20
                }

                R.id.lock_30 -> {
                    minutes = 30
                }

                R.id.lock_45 -> {
                    minutes = 45
                }

                R.id.lock_60 -> {
                    minutes = 60
                }
            }
            startService()
            val unlockReceiver = UnlockReceiver()
            val intentFilter = IntentFilter()
            intentFilter.addAction("android.intent.action.USER_PRESENT");

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                registerReceiver(unlockReceiver, intentFilter, RECEIVER_EXPORTED)
            } else {
                registerReceiver(unlockReceiver, intentFilter)
            }
            if (minutes == 0L) {
                saveLockSettingAndLock(binding.lockTime.text.toString().toLong() * 60 * 1000)
            } else {
                lockLater(minutes)
            }
        }
        binding.lock0.setOnClickListener(listener)
        binding.lock10.setOnClickListener(listener)
        binding.lock20.setOnClickListener(listener)
        binding.lock30.setOnClickListener(listener)
        binding.lock45.setOnClickListener(listener)
        binding.lock60.setOnClickListener(listener)
        binding.privaryBtn.setOnClickListener {
            val intent = Intent(this, PrivacyActivity::class.java)
            startActivity(intent)
        }
        val granted = devicePolicyManager?.isAdminActive(componentName!!)
        if (granted == false) {
            AlertDialog.Builder(this)
                .setTitle("权限请求")
                .setMessage("锁屏功能需要设备管理权限，请授予权限。")
                .setPositiveButton("确定") { _, _ ->
                    val intent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)
                    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName)
                    intent.putExtra(
                        DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                        "锁屏功能需要设备管理权限"
                    )
                    enableAdminLauncher.launch(intent)
                }
                .setNegativeButton("取消", null)
                .show()
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (checkSelfPermission(
                    Manifest.permission.POST_NOTIFICATIONS
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                requestPermissions(
                    arrayOf(Manifest.permission.POST_NOTIFICATIONS),
                    1
                )
            }
        }
        lifecycleScope.launch {
            while (isActive) {
                showRemainingMinutesToLock()
                delay(1000)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showRemainingMinutesToLock() {
        val sharedPreferences =
            applicationContext.getSharedPreferences(Constants.APP_PREF, MODE_PRIVATE)
        val startTime = sharedPreferences.getLong(Constants.LOCK_START_TIME, 0)

        if (startTime > System.currentTimeMillis()) {
            //锁屏倒计时开始了
            binding.cancelLockRow.visibility = View.VISIBLE
            val remainingMilliseconds = startTime - System.currentTimeMillis()
            val remainingMinutes = remainingMilliseconds / 60000
            val remainingSeconds = (remainingMilliseconds % 60000) / 1000
            binding.remainingMinutesToLock.text =
                "${remainingMinutes}分钟${remainingSeconds}秒后锁屏"

            binding.cancelButton.setOnClickListener {
                sharedPreferences.edit() { remove(Constants.LOCK_START_TIME) }
                binding.cancelLockRow.visibility = View.GONE
            }
        } else {
            binding.cancelLockRow.visibility = View.GONE
        }
    }

    private fun lockLater(delayMinutes: Long) {
        val lockTime = binding.lockTime.text.toString().toLong() * 60 * 1000
        val sharedPreferences =
            applicationContext.getSharedPreferences(Constants.APP_PREF, MODE_PRIVATE)
        sharedPreferences.edit() {
            putLong(Constants.LOCK_TIME, lockTime + System.currentTimeMillis())
            putBoolean(Constants.ALLOW_UNLOCK, binding.allowUnlock.isChecked)
            putLong(
                Constants.LOCK_START_TIME,
                delayMinutes * 60 * 1000 + System.currentTimeMillis()
            )
        }

        val workManager = WorkManager.getInstance(this@MainActivity)
        workManager.enqueue(
            OneTimeWorkRequest.Builder(LockScreenWorker::class.java)
                .setInitialDelay(delayMinutes, TimeUnit.MINUTES)
                .build()
        )
        showRemainingMinutesToLock()
//        moveTaskToBack(true)
    }

    private fun startService(): Boolean {
        val serviceIntent = Intent(this@MainActivity, LockScreenService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            if (checkSelfPermission(Manifest.permission.FOREGROUND_SERVICE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                    arrayOf(Manifest.permission.FOREGROUND_SERVICE),
                    1
                )
                return true
            }
        }
        try {
            startForegroundService(serviceIntent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    override fun onResume() {
        super.onResume()
        // 检查锁屏时间
        val sharedPreferences =
            applicationContext.getSharedPreferences(Constants.APP_PREF, MODE_PRIVATE)
        val lockTime = sharedPreferences.getLong(Constants.LOCK_TIME, 0)
        val lockStartTime = sharedPreferences.getLong(Constants.LOCK_START_TIME, 0)

        if (System.currentTimeMillis() < lockTime && System.currentTimeMillis() > lockStartTime) {
            val allowUnlock = sharedPreferences.getBoolean(Constants.ALLOW_UNLOCK, true)
            binding.allowUnlock.isChecked = allowUnlock
            if (allowUnlock) {
                showUnlockDialog()
            } else {
                lock()
            }
        }
    }

    private fun showUnlockDialog() {
        if (mAlertDialog != null && mAlertDialog!!.isShowing) {
            return
        }

        val sharedPreferences = getSharedPreferences(Constants.APP_PREF, MODE_PRIVATE)
        sharedPreferences.edit() { putBoolean(Constants.UNLOCKING, true) }
        val remainingMilliseconds =
            sharedPreferences.getLong(Constants.LOCK_TIME, 0) - System.currentTimeMillis()
        val remainingMinutes = remainingMilliseconds / 60000
        val remainingSeconds = (remainingMilliseconds % 60000) / 1000
        mAlertDialog = AlertDialog.Builder(this)
            .setTitle("解除屏幕锁定")
            .setMessage("自动解锁还剩${remainingMinutes}分钟${remainingSeconds}秒，是否解锁？")
            .setPositiveButton("是") { _, _ ->
                Toast.makeText(this, "屏幕锁定已解除", Toast.LENGTH_SHORT).show()
                sharedPreferences.edit() {
                    remove(Constants.LOCK_TIME)
                    remove(Constants.UNLOCKING)
                }
            }
            .setNegativeButton("否") { _, _ ->
                sharedPreferences.edit() { remove(Constants.UNLOCKING) }
                Toast.makeText(this, "马上锁屏", Toast.LENGTH_SHORT).show()
                binding.counterclockwise.postDelayed({ lock() }, 1000)
            }.setOnDismissListener {
                mAlertDialog = null
            }
            .show()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun lock() {
        devicePolicyManager!!.lockNow()
        binding.counterclockwise.text = getString(R.string.slogan)
    }

    private fun saveLockSettingAndLock(lockTime: Long) {
        val sharedPreferences =
            getSharedPreferences(Constants.APP_PREF, MODE_PRIVATE)
        sharedPreferences.edit() {
            putLong(Constants.LOCK_TIME, lockTime + System.currentTimeMillis())
            putBoolean(Constants.ALLOW_UNLOCK, binding.allowUnlock.isChecked)
            remove(Constants.LOCK_START_TIME)
        }
        binding.cancelLockRow.visibility = View.GONE
        lock()
//        moveTaskToBack(true)
    }
}